import path from 'path';
import { defineConfig } from 'vite';

import styleImport from 'vite-plugin-style-import';
import reactRefresh from '@vitejs/plugin-react-refresh';

const envConfig = require('./proxy.config');
const pkg = require('./package.json');

const devDomain = envConfig.getDomain();

const NODE_ENV = process.env.NODE_ENV || 'development';
const env = { development: 'test', production: 'prd' }[NODE_ENV];
const PORT = process.env.PORT || 10000;
const PROXY = process.env.ip || process.env.IP;

const isDev = env === 'test'; // build mode: development

const publicPath = '/';

const cookies = {
  current: null,
};

// 代理配置
const configure = (proxy, opts) => {
  proxy.on('proxyReq', (proxyReq, req, res) => {
    proxyReq._headers.cookie = proxyReq._headers.cookie || cookies.current;
    // console.log('\nproxyReq headers', proxyReq._headers);
  });

  proxy.on('proxyRes', (proxyRes, req, res) => {
    // console.log('\nstatusCode', proxyRes.statusCode);
    // console.log('\nstatusMessage', proxyRes.statusMessage);
    // console.log('\nheaders', proxyRes.headers);

    proxyRes.headers['access-control-allow-origin'] = req.headers['origin'];

    if (proxyRes.headers['set-cookie'] !== undefined) {
      // console.log('** SET-COOKIE: ', proxyRes.headers['set-cookie']);
      cookies.current = proxyRes.headers['set-cookie']
        .map((d) => d.replace(/Path=.+$/, ''))
        .join(';');
      // console.log('cookies.current', cookies.current);
      proxyRes.headers['set-cookie'] = proxyRes.headers['set-cookie'].map((d) =>
        d.replace(/Domain=\w+\.\w+;/, ``)
      );
    }
  });

  proxy.on('error', (err, req, res) => {
    console.log('err', err);
  });
};

const config = {
  plugins: [
    reactRefresh(),
    styleImport({
      libs: [
        {
          libraryName: 'antd-mobile',
          esModule: true,
          resolveStyle: (name) => {
            return `antd-mobile/es/${name}/style/css`;
          },
        },
        {
          libraryName: 'antd',
          esModule: true,
          resolveStyle: (name) => {
            return `antd/es/${name}/style/css`;
          },
        },
      ],
    }),
  ],
  /**
   * 在生产中服务时的基本公共路径。
   * @default '/'
   */
  base: publicPath,
  /**
   * 与“根”相关的目录，构建输出将放在其中。如果目录存在，它将在构建之前被删除。
   * @default 'dist'
   */
  outDir: 'dist',
  emitManifest: true,
  // 引入第三方的配置
  optimizeDeps: {
    // include: [],
    // exclude: [],
  },
  resolve: {
    alias: {
      '~': path.resolve(__dirname, './src'),
    },
  },
  //这里注意，键名是scss不是sass！一字之差能让你折腾好久
  css: {
    preprocessorOptions: {
      scss: {
        // 自动导入全局样式
        // globalScss: "@import '~/styles/index.scss';",
      },
    },
  },
  define: {
    __client__: true,
    __dev__: isDev,
    __local_proxy__: !!PROXY,
  },
  build: {
    target: 'modules', // browsers with native ES module support.
    outDir: `assets`,
    assetsDir: '',
    emptyOutDir: true,
  },
  server: {
    port: PORT,
    cors: true,
    // 是否自动在浏览器打开
    open: false,
    // 是否开启 https
    https: false,
    // 服务端渲染
    ssr: false,
    historyApiFallback: {
      rewrites: [{ from: /^\/$/, to: '/index.html' }],
    },
    proxy: {
      '/api': {
        target: `${devDomain.target}`,
        headers: {
          'origin': `${devDomain.origin}`,
          'referer': `${devDomain.origin}`,
          'sec-fetch-site': 'same-site',
          'sec-fetch-mode': 'cors',
          'sec-fetch-dest': 'empty',
        },
        changeOrigin: true, // 是否跨域
        secure: true, // 是否https接口
        configure,
      },
    },
  },
};

export default defineConfig(config);
